﻿#include "sysdeptcontroller.h"
#include "utils/dictionaryutil.h"

SysDeptController::SysDeptController()
{
    m_pHelper = DbMgr::instance()->getHelper();
    m_mapFunc.insert("/sys/dept/depttype",          &SysDeptController::deptType);        //获取部门类型
    m_mapFunc.insert("/sys/dept/deptname",          &SysDeptController::deptName);        //获取部门名称
    m_mapFunc.insert("/sys/dept/deptnamebyuserid",  &SysDeptController::deptNameByUserId);//获取用户部门
    m_mapFunc.insert("/sys/dept/datagrid",          &SysDeptController::datagrid);        //获取部门列表
    m_mapFunc.insert("/sys/dept/save",              &SysDeptController::save);            //保存部门信息
    m_mapFunc.insert("/sys/dept/delete",            &SysDeptController::delDept);         //删除部门信息

}

void SysDeptController::service(HttpRequest& request, HttpResponse& response)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString access_token = request.getParameter("access_token");
    QString username = JwtUtil::getUsername(access_token);
    if(username == NULL || username.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    SysUser visitUser;
    if(!m_pHelper->selectUserByName(visitUser, username))
    {
        ret.failedMsg(QStringLiteral("用户不存在，操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QByteArray path = request.getPath().toLower();
    if(m_mapFunc.contains(path))
    {
        pServFunc func = m_mapFunc.value(path);
        (this->*func)(request, response, visitUser);
    }
}

//获取部门类型
//http://localhost:9004/sys/dept/deptType?access_token=?
//{"code":0,"data":[{"label":"集团","value":"0"},{"label":"公司","value":"1"},{"label":"部门","value":"2"},{"label":"小组","value":"3"}],"msg":""}
void SysDeptController::deptType(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QMap<QString, QString> map = DictionaryUtil::instance()->getDictionary("dept_type");

    QMap<QString, QJsonObject> orderMap;
    foreach (QString key, map.keys()) {
         QJsonObject obj;
         obj.insert("label", key);
         obj.insert("value", map[key]);
         orderMap.insert(map[key], obj);
    }
    QJsonArray dataArray;
    foreach (QString key, orderMap.keys())
        dataArray.append(orderMap[key]);
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);
}

//获取部门名称
//http://localhost:9004/sys/dept/deptName?id=-1&access_token=?
//{"code":0,"data":{"orderNo":0},"msg":""}
//{"code":0,"data":{"createDate":1551945180000,"createName":"system","deptNo":"0021","id":"?","memo":"","name":"开发部","orderNo":1,"parentId":"?","shortName":"开发部","type":"2","versions":0},"msg":""}
void SysDeptController::deptName(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString idParam = request.getParameter("id");
    int id = idParam.toInt();
    if(id <= 0)
    {
        ResponseUtil::replyJson(response, ret);
        return;
    }

    SysDept dept;
    dept.setId(id);
    if(!m_pHelper->selectEntityById(&dept))
    {
        ret.failedMsg(QStringLiteral("部门不存在"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QJsonObject obj = dept.toJson();
    ret.setData(obj);
    ResponseUtil::replyJson(response, ret);
}

 //获取用户部门
//http://localhost:9004/sys/dept/deptNameByUserId?userId=?&access_token=?
//{"code":0,"data":{"createDate":1552011695000,"createName":"system","deptNo":"00067","id":"?","versions":0,
//"memo":"","name":"市场部","orderNo":7,"parentId":"?","shortName":"市场部","type":"2"},"msg":""}
void SysDeptController::deptNameByUserId(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString userId = request.getParameter("userId");

    SysUser user;
    user.setId(userId.toInt());
    if(!m_pHelper->selectEntityById(&user))
    {
        ret.failedMsg(QStringLiteral("用户不存在"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    SysDept dept;
    dept.setId(user.getDeptId());
    if(!m_pHelper->selectEntityById(&dept))
    {
        ret.failedMsg(QStringLiteral("部门不存在"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QJsonObject obj = dept.toJson();
    ret.setData(obj);
    ResponseUtil::replyJson(response, ret);

}

//获取部门列表
//http://localhost:9004/sys/dept/datagrid?field=orderNo&order=asc&deptNo=33&shortName=&access_token=?
//{"code":0,"count":10,"data":[{"createDate":1551945222000,"createName":"system","deptNo":"00211","id":"5e5ae11bae54d1ce1e8512f138cb9c75","memo":"4","name":"开发1组","orderNo":1,"parentId":"bccea46c2e2ff20592ca91a245313d41","shortName":"开发1组","type":"小组","updateDate":1692335820000,"updateName":"admin","versions":6},{"createDate":1576041561000,"createName":"admin","deptNo":"9888","id":"829927e2cc55f3ab61bca76cbc93528e","memo":"1","name":"gg","orderNo":1,"parentId":"88f8b2b2c14220d7c923e037b6bbbd53","shortName":"测试部","type":"部门","updateDate":1576041665000,"updateName":"admin","versions":9},{"createDate":1551942489000,"createName":"system","deptNo":"002","id":"88f8b2b2c14220d7c923e037b6bbbd53","memo":"","name":"江苏众禾","orderNo":1,"parentId":"decde2a1436ea808ef7634e404a32ba0","shortName":"江苏众禾","type":"公司","versions":0},{"createDate":1552038615000,"createName":"system","deptNo":"000987","id":"acf479c72e6308c64a4fcfe202b895e1","memo":"1","name":"商务部","orderNo":1,"parentId":"77124de3c7cff7680d08a80621cfe924","shortName":"商务部","type":"部门","updateDate":1575269257000,"updateName":"admin","versions":2},{"createDate":1551945180000,"createName":"system","deptNo":"0021","id":"bccea46c2e2ff20592ca91a245313d41","memo":"","name":"开发部","orderNo":1,"parentId":"88f8b2b2c14220d7c923e037b6bbbd53","shortName":"开发部","type":"部门","versions":0},{"createDate":1551942460000,"createName":"system","deptNo":"001","id":"decde2a1436ea808ef7634e404a32ba0","memo":"","name":"众禾集团","orderNo":1,"parentId":"-1","shortName":"众禾集团","type":"集团","versions":0},{"createDate":1551945097000,"createName":"system","deptNo":"003","id":"77124de3c7cff7680d08a80621cfe924","memo":"","name":"上海华谷","orderNo":2,"parentId":"decde2a1436ea808ef7634e404a32ba0","shortName":"上海华谷","type":"公司","updateDate":1577424555000,"updateName":"admin","versions":3},{"createDate":1551945198000,"createName":"system","deptNo":"0022","id":"b65ce375c39071b8ed7c88c82569b2e3","memo":"","name":"财务部","orderNo":2,"parentId":"88f8b2b2c14220d7c923e037b6bbbd53","shortName":"财务部","type":"部门","versions":0},{"createDate":1552011695000,"createName":"system","deptNo":"00067","id":"6575819c40dccab6e91ef10306e24c9f","memo":"","name":"市场部","orderNo":7,"parentId":"88f8b2b2c14220d7c923e037b6bbbd53","shortName":"市场部","type":"部门","versions":0},{"createDate":1552011777000,"createName":"system","deptNo":"00098","id":"b311af8d9e65ce2b5a5f8825626ee68f","memo":"1","name":"客服部","orderNo":9,"parentId":"88f8b2b2c14220d7c923e037b6bbbd53","shortName":"客服部","type":"部门","updateDate":1577933554000,"updateName":"admin","versions":1}],"msg":""}
void SysDeptController::datagrid(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    QString field = request.getParameter("field");
    QString order = request.getParameter("order");
    QString deptNo = request.getParameter("deptNo");
    QString shortName = request.getParameter("shortName");

    QStringList condi;
    if(!deptNo.isEmpty())
        condi << "dept_no like '%" + deptNo + "%'";
    if(!shortName.isEmpty())
        condi << "short_name like '%" + shortName + "%'";

    QList<SysDept> deptList;
    m_pHelper->getDeptList(deptList, condi, "");

    QMap<QString, QString> map = DictionaryUtil::instance()->getDictionary("dept_type");
    QJsonArray dataArray;
    foreach (SysDept dept, deptList) {
        QJsonObject obj = dept.toJson();

         if(dept.getParentId() <= 0)
             obj.insert("parentId",     "-1");

         foreach (QString key, map.keys()) {
             if(map[key] == dept.getType())
             {
                 obj.insert("type",  key);
                 break;
             }
         }
         if(!obj.contains("type"))
             obj.insert("type",  dept.getType());

         dataArray.append(obj);
    }

    ResultJson ret(0, true, QStringLiteral(""));
    ret.setProp("count", deptList.size());
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);
}

//保存部门信息
//http://localhost:9004/sys/dept/save
/*
id: 5e5ae11bae54d1ce1e8512f138cb9c75
deptNo: 00211
name: 开发1组
shortName: 开发1组
parentName: 开发部
parentId: bccea46c2e2ff20592ca91a245313d41
type: 3
orderNo: 1
memo: 4
access_token: ?
*/
void SysDeptController::save(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{

    SysDept dept;

    QString parentIdParam = request.getParameter("parentId");
    if(parentIdParam.isEmpty())
        dept.setParentId(-1);
    else
        dept.setParentId(parentIdParam.toInt());

    QString orderNoParam = request.getParameter("orderNo");
    if(!orderNoParam.isEmpty())
        dept.setOrderNo(orderNoParam.toInt());

    dept.setDeptNo(request.getParameter("deptNo"));
    dept.setName(request.getParameter("name"));
    dept.setShortName(request.getParameter("shortName"));
    dept.setType(request.getParameter("type"));
    dept.setMemo(request.getParameter("memo"));

    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString idParam = request.getParameter("id");

    if(!idParam.isEmpty())
    {
        dept.setId(idParam.toInt());
        dept.setUpdateDate(QDateTime::currentDateTime());
        dept.setUpdateName(visitUser.getUserName());

        if(!m_pHelper->updateEntity(&dept))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
        }

    }
    else
    {
        dept.setCreateDate(QDateTime::currentDateTime());
        dept.setCreateName(visitUser.getUserName());
        dept.setUpdateDate(QDateTime::currentDateTime());
        dept.setUpdateName(visitUser.getUserName());
        dept.setVersion(1);

        if(!m_pHelper->insertEntity(&dept))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
        }
    }
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::SAVE, QStringLiteral("保存部门信息"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("保存部门信息成功"));
    m_pHelper->insertEntity(&log);
}

//删除部门信息
//http://localhost:9004/sys/dept/delete
//{"code":0,"success":true,"msg":"操作成功","data":null}
/*
id: 2787588c893f2c8bf9966c7fa29063f3
access_token: ?
*/
void SysDeptController::delDept(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{

    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString idParam = request.getParameter("id");

    if(idParam.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    int id = idParam.toInt();

    QStringList condi;
    condi << "dept_id=" + id;
    QList<SysUser> userList;
    m_pHelper->getUserList(userList, condi, "");
    if(userList.size() > 0)
    {
        ret.failedMsg(QStringLiteral("该部门下存在用户，不能直接删除"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    condi.clear();
    condi << "parent_id=" + id;
     QList<SysDept> deptList;
    m_pHelper->getDeptList(deptList, condi, "");
    if(deptList.size() > 0)
    {
        ret.failedMsg(QStringLiteral("该部门下存在子部门，不能直接删除"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    SysDept dept;
    dept.setId(id);
    if(!m_pHelper->deleteEntity(&dept))
    {
        ret.failedMsg(QStringLiteral("操作失败"));
    }

    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::DEL, QStringLiteral("删除部门信息"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("删除部门信息成功"));
    m_pHelper->insertEntity(&log);
}
